<?php
class Material {
    private $conn;
    private $auth;

    public function __construct(PDO $conn, Auth $auth) {
        $this->conn = $conn;
        $this->auth = $auth;
    }

/**
 * 上传/更新订单素材
 */
public function upload(): void {
    // 首先验证用户登录状态
    $userId = $this->auth->getUserId();
    if ($userId === 0) {
        // 保持 HTTP 状态码为 200，只在 JSON 响应中设置错误码
        echo json_encode([
            'code' => 401,
            'message' => '请先登录'
        ]);
        return;
    }

    $this->conn->beginTransaction();
    
    try {
        $data = json_decode(file_get_contents('php://input'), true);
        
        // 验证输入数据
        if (empty($data)) {
            throw new Exception("请求数据不能为空", 400);
        }

        // 验证必填字段
        if (empty($data['order_id'])) {
            throw new Exception("缺少订单ID", 400);
        }

        $orderId = (int)$data['order_id'];

        // 检查订单是否存在且属于当前用户
        $stmt = $this->conn->prepare("
            SELECT id FROM orders 
            WHERE id = :order_id AND creator_id = :creator_id
            LIMIT 1
        ");
        $stmt->execute([
            ':order_id' => $orderId,
            ':creator_id' => $userId
        ]);
        
        if (!$stmt->fetch()) {
            throw new Exception("订单不存在或无权操作", 403);
        }

        // 检查是否已有素材记录
        $stmt = $this->conn->prepare("
            SELECT id FROM materials 
            WHERE order_id = :order_id
            LIMIT 1
        ");
        $stmt->execute([':order_id' => $orderId]);
        $materialExists = $stmt->fetch();

        // 准备素材数据
        $materialData = [
            ':order_id' => $orderId,
            ':m_link' => $data['m_link'] ?? null,
            ':r_link' => $data['r_link'] ?? null,
            ':t_link' => $data['t_link'] ?? null,
            ':is_preview' => isset($data['is_preview']) ? (int)$data['is_preview'] : 0,
            ':abnormal_remark' => $data['abnormal_remark'] ?? null,
            ':uploader_id' => $userId
        ];

        if ($materialExists) {
            // 更新现有素材记录
            $stmt = $this->conn->prepare("
                UPDATE materials SET
                    m_link = :m_link,
                    r_link = :r_link,
                    t_link = :t_link,
                    is_preview = :is_preview,
                    abnormal_remark = :abnormal_remark,
                    uploader_id = :uploader_id,
                    update_time = NOW()
                WHERE order_id = :order_id
            ");
        } else {
            // 创建新素材记录
            $stmt = $this->conn->prepare("
                INSERT INTO materials (
                    order_id, m_link, r_link, t_link, 
                    is_preview, abnormal_remark, uploader_id
                ) VALUES (
                    :order_id, :m_link, :r_link, :t_link,
                    :is_preview, :abnormal_remark, :uploader_id
                )
            ");
        }

        if (!$stmt->execute($materialData)) {
            throw new Exception("素材保存失败: " . implode(', ', $stmt->errorInfo()), 500);
        }

        // 更新订单的素材状态
        $hasMaterial = (!empty($data['m_link']) || !empty($data['r_link']) || !empty($data['t_link'])) ? 1 : 0;
        $stmt = $this->conn->prepare("
            UPDATE orders SET
                has_material = :has_material,
                update_time = NOW()
            WHERE id = :order_id
        ");
        
        if (!$stmt->execute([
            ':has_material' => $hasMaterial,
            ':order_id' => $orderId
        ])) {
            throw new Exception("订单状态更新失败", 500);
        }

        $this->conn->commit();

        echo json_encode([
            'code' => 200,
            'msg' => '素材上传成功',
            'data' => [
                'order_id' => $orderId,
                'has_material' => $hasMaterial,
                'material_exists' => (bool)$materialExists
            ]
        ]);

    } catch (Exception $e) {
        if ($this->conn->inTransaction()) {
            $this->conn->rollBack();
        }
        
        error_log("Material upload error: " . $e->getMessage());
        
        // 保持 HTTP 状态码为 200，只在 JSON 响应中设置错误码
        echo json_encode([
            'code' => $e->getCode() ?: 500,
            'message' => $e->getMessage()
        ]);
    }
}
   /**
 * 获取订单素材信息（包含订单基本信息）
 */
public function getByOrder(): void {
    try {
        $userId = $this->auth->getUserId();
        if ($userId === 0) {
            throw new Exception("请先登录", 401);
        }

        if (empty($_GET['order_id'])) {
            throw new Exception("缺少订单ID参数", 400);
        }

        $orderId = (int)$_GET['order_id'];

        // 查询订单基本信息
        $stmt = $this->conn->prepare("
            SELECT 
                o.id, o.order_number, o.customer_name, o.phone, o.type,
                o.start_date, o.end_date, o.channel, 
                o.deposit, o.final_payment, o.total_amount,
                o.payment_method, o.status, o.create_time as order_create_time,
                o.update_time as order_update_time, o.has_material,
                o.member_id, o.member_name
            FROM orders o
            WHERE o.id = :order_id
            LIMIT 1
        ");
        $stmt->execute([':order_id' => $orderId]);
        $order = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$order) {
            throw new Exception("订单不存在", 404);
        }

        // 查询素材信息
        $stmt = $this->conn->prepare("
            SELECT 
                m.id as material_id, m.m_link, m.r_link, m.t_link,
                m.is_preview, m.abnormal_remark,
                m.upload_time, m.update_time as material_update_time,
                u.username as uploader_name
            FROM materials m
            LEFT JOIN users u ON m.uploader_id = u.id
            WHERE m.order_id = :order_id
            LIMIT 1
        ");
        $stmt->execute([':order_id' => $orderId]);
        $material = $stmt->fetch(PDO::FETCH_ASSOC);

        // 合并订单和素材信息
        $result = $order;
        if ($material) {
            $result = array_merge($order, $material);
        } else {
            $result['material_id'] = null;
            $result['m_link'] = null;
            $result['r_link'] = null;
            $result['t_link'] = null;
            $result['is_preview'] = 0;
            $result['abnormal_remark'] = null;
            $result['upload_time'] = null;
            $result['material_update_time'] = null;
            $result['uploader_name'] = null;
        }

        // 格式化日期字段
        $dateFields = [
            'start_date', 'end_date', 'order_create_time', 'order_update_time',
            'upload_time', 'material_update_time'
        ];
        foreach ($dateFields as $field) {
            if (!empty($result[$field])) {
                $result[$field] = date('Y-m-d', strtotime($result[$field]));
            }
        }

        echo json_encode([
            'code' => 200,
            'data' => $result
        ]);

    } catch (Exception $e) {
        // 保持 HTTP 状态码为 200，只在 JSON 响应中设置错误码
        echo json_encode([
            'code' => $e->getCode() ?: 500,
            'message' => $e->getMessage()
        ]);
    }
}
 public function noback(): void {
    $this->conn->beginTransaction();
    
    try {
        $userId = $this->auth->getUserId();
        if ($userId === 0) {
            throw new Exception("请先登录", 401);
        }

        $data = json_decode(file_get_contents('php://input'), true);
        
        // 验证输入数据
        if (empty($data) || !isset($data['id'])) {
            throw new Exception("缺少订单ID参数", 400);
        }

        $orderId = (int)$data['id'];

        // 1. 首先检查订单当前状态
        $stmt = $this->conn->prepare("
            SELECT has_material FROM orders 
            WHERE id = :order_id AND creator_id = :creator_id
            LIMIT 1
        ");
        $stmt->execute([
            ':order_id' => $orderId,
            ':creator_id' => $userId
        ]);
        
        $currentStatus = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$currentStatus) {
            throw new Exception("订单不存在或无权操作", 403);
        }

        error_log("当前订单状态：has_material=" . $currentStatus['has_material']);

        // 2. 更新订单状态为无需备份
        $stmt = $this->conn->prepare("
            UPDATE orders SET
                has_material = 2,  -- 2表示无需备份状态
                update_time = NOW()
            WHERE id = :order_id
        ");
        
        $updateResult = $stmt->execute([':order_id' => $orderId]);
        
        if (!$updateResult) {
            $errorInfo = $stmt->errorInfo();
            error_log("更新订单状态失败：" . json_encode($errorInfo));
            throw new Exception("订单状态更新失败：" . $errorInfo[2], 500);
        }

        // 3. 检查实际影响的行数
        $rowCount = $stmt->rowCount();
        error_log("实际更新的行数：" . $rowCount);
        
        if ($rowCount === 0) {
            throw new Exception("未找到符合条件的订单记录", 404);
        }

        // 4. 删除关联的素材记录（如果有）
        $stmt = $this->conn->prepare("
            DELETE FROM materials 
            WHERE order_id = :order_id
        ");
        $deleteResult = $stmt->execute([':order_id' => $orderId]);
        
        if (!$deleteResult) {
            $errorInfo = $stmt->errorInfo();
            error_log("删除素材记录失败：" . json_encode($errorInfo));
            // 这里可以选择继续或回滚，根据业务需求决定
        }

        $this->conn->commit();

        // 5. 再次查询确认状态已更新
        $stmt = $this->conn->prepare("
            SELECT has_material FROM orders 
            WHERE id = :order_id
            LIMIT 1
        ");
        $stmt->execute([':order_id' => $orderId]);
        $updatedStatus = $stmt->fetch(PDO::FETCH_ASSOC);
        
        error_log("更新后的订单状态：has_material=" . $updatedStatus['has_material']);

        echo json_encode([
            'code' => 200,
            'message' => '订单已设置为无需备份',
            'data' => [
                'order_id' => $orderId,
                'has_material' => 2,
                'actual_updated_status' => $updatedStatus['has_material'] // 返回实际查询到的状态
            ]
        ]);

    } catch (Exception $e) {
        if ($this->conn->inTransaction()) {
            $this->conn->rollBack();
        }
        
        error_log("Material noback error: " . $e->getMessage());
        
        // 保持 HTTP 状态码为 200，只在 JSON 响应中设置错误码
        echo json_encode([
            'code' => $e->getCode() ?: 500,
            'message' => $e->getMessage(),
            'debug' => isset($errorInfo) ? $errorInfo : null
        ]);
    }
}
}